package com.myway.javafx.service;

import com.myway.javafx.config.PropertyConfig;
import com.myway.javafx.entity.GitPro;
import com.myway.javafx.util.ThreadManager;
import javafx.scene.control.TextArea;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 梁爽
 * @description GitService
 * @since 2022-01-27 14:49
 */
@Component
public class GitService {

    @Autowired
    private PropertyConfig propertyConfig;

    @Autowired
    private RestTemplate restTemplate;

    public void findAllPros(TextArea downlog, String path) throws IOException {
        String url = propertyConfig.getGiturl() + "/api/v4/projects?private_token=" + propertyConfig.getGittoken() + "&per_page=100&simple=true";
        int page = 1;
        List<GitPro> list = new ArrayList<>();
        while (true) {
            final ResponseEntity<GitPro[]> entity = restTemplate.getForEntity(url + "&page=" + page, GitPro[].class);
            final GitPro[] pros = entity.getBody();
            if (pros != null && pros.length > 0) {
                list.addAll(Arrays.asList(pros));
                page++;
            } else {
                break;
            }
        }
        downlog.appendText("总共 " + list.size() + " 个项目\r\n");
        downlog.appendText("开始下载------------\r\n");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + propertyConfig.getGittoken());
        url = propertyConfig.getGiturl() + "/api/v4/projects/:id/repository/archive.zip";
        HttpEntity<String> request = new HttpEntity<>(null, headers);


        ThreadManager.ThreadPollProxy pool = ThreadManager.getThreadPollProxy();

        String finalUrl = url;
        AtomicInteger i = new AtomicInteger(1);
        int size = list.size();
        list.forEach(tmp -> pool.execute(() -> {
            ResponseEntity<byte[]> resEntity = restTemplate.exchange(finalUrl.replace(":id", tmp.getId() + ""), HttpMethod.GET, request, byte[].class);
            if (resEntity.getStatusCodeValue() == 200) {
                try {
                    Files.write(Paths.get(path).resolve(tmp.getName() + ".zip"), resEntity.getBody());
                    downlog.appendText("下载: " + (i.get()) + " / " + size + " 成功 "+tmp.getName()+"\r\n");
                } catch (IOException e) {
                    e.printStackTrace();
                    downlog.appendText("下载: " + (i.get()) + " / " + size + " 失败 "+tmp.getName()+"\r\n");
                }

            } else {
                downlog.appendText("下载: " + (i.get()) + " / " + size + " 失败\r\n");
            }
            i.getAndIncrement();
        }));
        pool.shutdown();
    }

}
